package com.ht.modules.system.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ht.aspect.annotation.AutoLog;
import com.ht.entity.*;
import com.ht.modules.system.entity.CommonConfig;
import com.ht.modules.system.entity.SysApk;
import com.ht.modules.system.entity.SysApkVo;
import com.ht.modules.system.mapper.CommonConfigMapper;
import com.ht.query.QueryGenerator;
import com.ht.modules.system.service.IApkService;
import com.ht.utils.DicConstants;
import com.ht.utils.oConvertUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.List;

/**
 *  apk版本升级
 */
@Slf4j
@Api(tags = "apk版本升级")
@RestController
@RequestMapping("/apk/sysApk")
public class ApkController {

    @Autowired
    private IApkService apkService;
    @Autowired
    private CommonConfigMapper commonConfigMapper;

    /**
     * 分页列表查询
     */
    @ApiOperation(value = "apk版本升级-分页列表查询", notes = "apk版本升级-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SysApkVo>> queryPageList(SysApkVo sysApkVo,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 @RequestParam(name = "column", defaultValue = "createTime") String column,
                                                 @RequestParam(name = "order", defaultValue = "desc") String order) {
        Result<IPage<SysApkVo>> result = new Result<>();
        Page<SysApkVo> page = new Page<>(pageNo, pageSize);
        page = apkService.list(page, sysApkVo, column, order);
        result.setSuccess(true);
        result.setResult(page);
        return result;
    }

    /**
     * 查询最新版本的apk
     *
     * @return 最新版本apk对象
     */
    @ApiOperation(value = "查询最新版本的apk", notes = "查询最新版本的apk")
    @GetMapping(value = "/queryNewVersion")
    public Result<SysApk> queryNewVersion() {
        Result<SysApk> result = new Result<>();
        QueryWrapper<SysApk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_newest", "0");
        queryWrapper.eq("del_flag", DicConstants.DEL_FLAG_WSC);
        SysApk newestApk = apkService.getOne(queryWrapper);
        result.setSuccess(true);
        result.setResult(newestApk);
        return result;
    }

    /**
     * 添加
     */
    @AutoLog(value = "apk版本升级-添加")
    @ApiOperation(value = "apk版本升级-添加", notes = "apk版本升级-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysApk sysApk) {
        Result<?> result = new Result<>();
        try {
            apkService.saveApk(sysApk);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败！" + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑
     */
    @AutoLog(value = "apk版本升级-编辑")
    @ApiOperation(value = "apk版本升级-编辑", notes = "apk版本升级-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysApk sysApk) {
        Result<?> result = new Result<>();
        SysApk sysApkEntity = apkService.getById(sysApk.getId());
        if (sysApkEntity == null) {
            result.error500("未找到对应实体");
        } else {
            apkService.updateById(sysApk);
            result.success("修改成功!");
        }
        return result;
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "apk版本升级-通过id删除")
    @ApiOperation(value = "apk版本升级-通过id删除", notes = "apk版本升级-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        Result<?> result = new Result<>();
        SysApk sysApk = apkService.getById(id);
        if (sysApk == null) {
            result.error500("未找到对应实体");
        } else {
            sysApk.setDelFlag(DicConstants.DEL_FLAG_YSC);
            apkService.updateById(sysApk);
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "apk版本升级-批量删除")
    @ApiOperation(value = "apk版本升级-批量删除", notes = "apk版本升级-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<?> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            apkService.updateBatchByIds("del_flag",
                    DicConstants.DEL_FLAG_YSC, ids.split(","));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     */
    @ApiOperation(value = "apk版本升级-通过id查询", notes = "apk版本升级-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SysApk> queryById(@RequestParam(name = "id") String id) {
        Result<SysApk> result = new Result<>();
        SysApk sysApk = apkService.getById(id);
        if (sysApk == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysApk);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysApk> queryWrapper = null;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                SysApk sysApk = JSON.parseObject(deString, SysApk.class);
                queryWrapper = QueryGenerator.initQueryWrapper(sysApk, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysApk> pageList = apkService.list(queryWrapper);
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "apk版本升级列表");
        mv.addObject(NormalExcelConstants.CLASS, SysApk.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("apk版本升级列表数据",
                "导出人:" + sysUser.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 获取到最新版的apk链接,制成二维码
     *
     * @param response 相应对象
     */
    @RequestMapping(value = "/generateQrCode")
    public void generateQrCode(HttpServletResponse response) {
        QueryWrapper<SysApk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_newest", "0");
        queryWrapper.eq("del_flag", DicConstants.DEL_FLAG_WSC);
        SysApk newestApk = apkService.getOne(queryWrapper);
        String result;
        LambdaQueryWrapper<CommonConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommonConfig::getDelFlag, DicConstants.DEL_FLAG_WSC);
        List<CommonConfig> commonConfigList = commonConfigMapper.selectList(wrapper);
        if (commonConfigList == null || commonConfigList.size() <= 0) {
            throw new RuntimeException("请检查系统通用配置！");
        }
        String apkDownloadUrl = commonConfigList.get(0).getApkDownloadUrl();
        if (newestApk != null && newestApk.getYuliu() != null) {
            result = apkDownloadUrl + newestApk.getYuliu();
        } else {
            result = "暂无最新版本,请联系管理员！！！";
        }
        BufferedImage image;
        try {
            image = createImage(result);
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static BufferedImage createImage(String content) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, 300, 300, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    /**
     * 生成ios二维码
     *
     * @return 二维码路径
     */
    @ApiOperation(value = "apk版本升级-生成ios二维码", notes = "apk版本升级-生成ios二维码")
    @PutMapping(value = "/getIOSQRcode")
    public Result<String> getIOSQRcode() {
        Result<String> result = new Result<>();
        try {
            String iosQRcode = apkService.getIOSQRcode();
            result.setResult(iosQRcode);
            result.success("操作成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败！" + e.getMessage());
        }
        return result;
    }

    /**
     * 通过版本号返回版本备注
     */
    @ApiOperation(value = "apk版本升级-通过版本号返回版本备注", notes = "apk版本升级-通过版本号返回版本备注")
    @GetMapping(value = "/getApkInfoByVersion")
    public Result<SysApk> getApkInfoByVersion(@RequestParam(name = "apkVersion") String apkVersion) {
        Result<SysApk> result = new Result<>();
        try {
            SysApk sysApk = apkService.getApkInfoByVersion(apkVersion);
            result.setResult(sysApk);
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败！" + e.getMessage());
        }
        return result;
    }

}
